package controllers

import (
	"net/http"
	"simple-crm/models"
	"simple-crm/services"
	"simple-crm/utils"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type UserController struct {
	db                *gorm.DB
	userService       *services.UserService
	permissionService *services.PermissionService
}

func NewUserController(db *gorm.DB, userService *services.UserService, permissionService *services.PermissionService) *UserController {
	return &UserController{
		db:                db,
		userService:       userService,
		permissionService: permissionService,
	}
}

// GetUserByID 获取用户详情
func (ctrl *UserController) GetUserByID(c *gin.Context) {
	id, _ := strconv.ParseUint(c.Param("id"), 10, 32)

	user, err := ctrl.userService.GetUserByID(uint(id))
	if err != nil {
		utils.ErrorWithMessage(c, "用户不存在")
		return
	}

	utils.SuccessWithData(c, user)
}

// GetUsers 获取用户列表
func (ctrl *UserController) GetUsers(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
	search := c.Query("search")
	status := c.Query("status")
	roleID := c.Query("role_id")

	users, total, err := ctrl.userService.GetUsers(page, limit, search, status, roleID)
	if err != nil {
		utils.ErrorWithMessage(c, "获取用户列表失败")
		return
	}

	utils.SuccessWithData(c, gin.H{
		"users": users,
		"total": total,
		"page":  page,
		"limit": limit,
	})
}

// CreateUser 创建用户
func (ctrl *UserController) CreateUser(c *gin.Context) {
	var req struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
		RealName string `json:"real_name" binding:"required"`
		Phone    string `json:"phone"`
		Email    string `json:"email"`
		Status   string `json:"status"`
		Gender   string `json:"gender"`
		RoleIDs  []uint `json:"role_ids"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ErrorWithMessage(c, "参数错误: "+err.Error())
		return
	}

	user := &models.User{
		Username: req.Username,
		Password: req.Password,
		RealName: req.RealName,
		Phone:    req.Phone,
		Email:    req.Email,
		Status:   req.Status,
		Gender:   req.Gender,
	}

	if user.Status == "" {
		user.Status = "active"
	}

	if err := ctrl.userService.CreateUser(user); err != nil {
		// 检查是否是用户名重复错误
		if err.Error() == "用户名已存在" {
			utils.ErrorWithMessage(c, "用户名已存在，请选择其他用户名")
			return
		}
		// 检查是否是数据库重复键错误
		if strings.Contains(err.Error(), "Duplicate entry") && strings.Contains(err.Error(), "idx_users_username") {
			utils.ErrorWithMessage(c, "用户名已存在，请选择其他用户名")
			return
		}
		if strings.Contains(err.Error(), "Duplicate entry") && strings.Contains(err.Error(), "idx_users_email") {
			utils.ErrorWithMessage(c, "邮箱已存在，请使用其他邮箱")
			return
		}
		utils.ErrorWithMessage(c, "创建用户失败: "+err.Error())
		return
	}

	// 分配角色
	currentUserID, _ := c.Get("user_id")
	for _, roleID := range req.RoleIDs {
		ctrl.permissionService.AssignRole(user.ID, roleID, currentUserID.(uint))
	}
	utils.SuccessWithMessage(c, "用户创建成功", nil)
}

// UpdateUser 更新用户
func (ctrl *UserController) UpdateUser(c *gin.Context) {
	id, _ := strconv.ParseUint(c.Param("id"), 10, 32)

	var req struct {
		RealName string `json:"real_name"`
		Phone    string `json:"phone"`
		Email    string `json:"email"`
		Status   string `json:"status"`
		Password string `json:"password"`
		Gender   string `json:"gender"`
		RoleIDs  []uint `json:"role_ids"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ErrorWithMessage(c, "参数错误: "+err.Error())
		return
	}

	updateData := map[string]interface{}{
		"real_name": req.RealName,
		"phone":     req.Phone,
		"email":     req.Email,
		"status":    req.Status,
		"gender":    req.Gender,
	}

	// 只有当密码不为空时才更新密码
	if req.Password != "" {
		updateData["password"] = req.Password
	}

	if err := ctrl.userService.UpdateUserByMap(uint(id), updateData); err != nil {
		// 检查是否是邮箱重复错误
		if strings.Contains(err.Error(), "Duplicate entry") && strings.Contains(err.Error(), "idx_users_email") {
			utils.ErrorWithMessage(c, "邮箱已存在，请使用其他邮箱")
			return
		}
		utils.ErrorWithMessage(c, "更新用户失败: "+err.Error())
		return
	}

	// 更新用户角色
	if len(req.RoleIDs) > 0 {
		// 先删除现有角色
		ctrl.db.Where("user_id = ?", id).Delete(&models.UserRole{})

		// 分配新角色
		currentUserID, _ := c.Get("user_id")
		for _, roleID := range req.RoleIDs {
			ctrl.permissionService.AssignRole(uint(id), roleID, currentUserID.(uint))
		}
	}

	utils.SuccessWithMessage(c, "用户更新成功", nil)
}

// DeleteUser 删除用户
func (ctrl *UserController) DeleteUser(c *gin.Context) {
	userID, _ := strconv.ParseUint(c.Param("id"), 10, 32)

	err := ctrl.userService.DeleteUser(uint(userID))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": false, "message": "删除用户失败"})
		return
	}

	utils.SuccessWithMessage(c, "用户删除成功", nil)
}

// AssignRole 分配角色给用户
func (ctrl *UserController) AssignRole(c *gin.Context) {
	userID, _ := strconv.ParseUint(c.Param("id"), 10, 32)
	roleID, _ := strconv.ParseUint(c.Param("role_id"), 10, 32)

	currentUserID, _ := c.Get("user_id")
	if err := ctrl.permissionService.AssignRole(uint(userID), uint(roleID), currentUserID.(uint)); err != nil {
		utils.ErrorWithMessage(c, "分配角色失败: "+err.Error())
		return
	}

	utils.SuccessWithMessage(c, "角色分配成功", nil)
}

// AssignUserRole 分配用户角色
func (ctrl *UserController) AssignUserRole(c *gin.Context) {
	userID, _ := strconv.ParseUint(c.Param("id"), 10, 32)

	var req struct {
		RoleIDs []uint `json:"role_ids" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ErrorWithMessage(c, "参数错误: "+err.Error())
		return
	}

	// 先删除现有角色
	ctrl.db.Where("user_id = ?", userID).Delete(&models.UserRole{})

	// 分配新角色
	currentUserID, _ := c.Get("user_id")
	for _, roleID := range req.RoleIDs {
		ctrl.permissionService.AssignRole(uint(userID), roleID, currentUserID.(uint))
	}

	utils.SuccessWithMessage(c, "角色分配成功", nil)
}

// RemoveRole 移除用户角色
func (ctrl *UserController) RemoveRole(c *gin.Context) {
	userID, _ := strconv.ParseUint(c.Param("id"), 10, 32)
	roleID, _ := strconv.ParseUint(c.Param("role_id"), 10, 32)

	// 删除用户角色关联
	result := ctrl.db.Where("user_id = ? AND role_id = ?", userID, roleID).Delete(&models.UserRole{})
	if result.Error != nil {
		utils.ErrorWithMessage(c, "移除角色失败: "+result.Error.Error())
		return
	}

	utils.SuccessWithMessage(c, "角色移除成功", nil)
}

// GetUserRoles 获取用户角色
func (ctrl *UserController) GetUserRoles(c *gin.Context) {
	userID, _ := strconv.ParseUint(c.Param("id"), 10, 32)

	roles, err := ctrl.userService.GetUserRoles(uint(userID))
	if err != nil {
		utils.ErrorWithMessage(c, "获取用户角色失败: "+err.Error())
		return
	}

	utils.SuccessWithData(c, roles)
}

// GetUserStats 获取用户统计信息
func (ctrl *UserController) GetUserStats(c *gin.Context) {
	stats, err := ctrl.userService.GetUserStats()
	if err != nil {
		utils.ErrorWithMessage(c, "获取统计信息失败: "+err.Error())
		return
	}

	utils.SuccessWithData(c, stats)
}

// BatchDeleteUsers 批量删除用户
func (ctrl *UserController) BatchDeleteUsers(c *gin.Context) {
	var req struct {
		UserIDs []uint `json:"user_ids" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ErrorWithMessage(c, "参数错误: "+err.Error())
		return
	}

	err := ctrl.userService.BatchDeleteUsers(req.UserIDs)
	if err != nil {
		utils.ErrorWithMessage(c, "批量删除失败: "+err.Error())
		return
	}

	utils.SuccessWithMessage(c, "批量删除成功", nil)
}

// ResetPassword 重置用户密码
func (ctrl *UserController) ResetPassword(c *gin.Context) {
	id, _ := strconv.ParseUint(c.Param("id"), 10, 32)

	var req struct {
		NewPassword string `json:"new_password" binding:"required,min=6"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ErrorWithMessage(c, "参数错误: "+err.Error())
		return
	}

	err := ctrl.userService.ResetPassword(uint(id), req.NewPassword)
	if err != nil {
		utils.ErrorWithMessage(c, "重置密码失败: "+err.Error())
		return
	}

	utils.SuccessWithMessage(c, "密码重置成功", nil)
}

// ToggleUserStatus 切换用户状态
func (ctrl *UserController) ToggleUserStatus(c *gin.Context) {
	id, _ := strconv.ParseUint(c.Param("id"), 10, 32)

	var req struct {
		Status string `json:"status" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ErrorWithMessage(c, "参数错误: "+err.Error())
		return
	}

	updateData := map[string]interface{}{
		"status": req.Status,
	}

	if err := ctrl.userService.UpdateUserByMap(uint(id), updateData); err != nil {
		utils.ErrorWithMessage(c, "切换状态失败: "+err.Error())
		return
	}

	utils.SuccessWithMessage(c, "状态切换成功", nil)
}

// CheckUserExists 检查用户名是否存在
func (ctrl *UserController) CheckUserExists(c *gin.Context) {
	username := c.Query("username")
	excludeID := c.Query("exclude_id")

	var count int64
	query := ctrl.db.Model(&models.User{}).Where("username = ?", username)
	if excludeID != "" {
		query = query.Where("id != ?", excludeID)
	}
	query.Count(&count)

	utils.SuccessWithData(c, gin.H{"exists": count > 0})
}

// CheckEmailExists 检查邮箱是否存在
func (ctrl *UserController) CheckEmailExists(c *gin.Context) {
	email := c.Query("email")
	excludeID := c.Query("exclude_id")

	var count int64
	query := ctrl.db.Model(&models.User{}).Where("email = ?", email)
	if excludeID != "" {
		query = query.Where("id != ?", excludeID)
	}
	query.Count(&count)

	utils.SuccessWithData(c, gin.H{"exists": count > 0})
}

// GetUserLoginHistory 获取用户登录历史
func (ctrl *UserController) GetUserLoginHistory(c *gin.Context) {
	userID, _ := strconv.ParseUint(c.Param("id"), 10, 32)
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))

	history, total, err := ctrl.userService.GetUserLoginHistory(uint(userID), page, pageSize)
	if err != nil {
		utils.ErrorWithMessage(c, "获取登录历史失败: "+err.Error())
		return
	}

	utils.SuccessWithData(c, gin.H{
		"list":  history,
		"total": total,
		"page":  page,
		"size":  pageSize,
	})
}

// GetUserProfile 获取当前用户资料
func (ctrl *UserController) GetUserProfile(c *gin.Context) {
	userID, _ := c.Get("user_id")

	// 检查权限 - 暂时跳过权限检查
	// if !ctrl.permissionService.CheckUserPermission(userID, "system.user.view") {
	//	c.JSON(http.StatusForbidden, gin.H{"success": false, "message": "权限不足"})
	//	return
	// }

	user, err := ctrl.userService.GetUserByID(userID.(uint))
	if err != nil {
		utils.ErrorWithMessage(c, "获取用户信息失败: "+err.Error())
		return
	}

	utils.SuccessWithData(c, user)
}

// UpdateUserProfile 更新当前用户资料
func (ctrl *UserController) UpdateUserProfile(c *gin.Context) {
	userID, _ := c.Get("user_id")

	// 检查权限 - 暂时跳过权限检查
	// if !ctrl.permissionService.CheckUserPermission(userID, "system.user.edit") {
	//	c.JSON(http.StatusForbidden, gin.H{"success": false, "message": "权限不足"})
	//	return
	// }

	var req struct {
		RealName string `json:"real_name" binding:"required"`
		Phone    string `json:"phone"`
		Email    string `json:"email"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ErrorWithMessage(c, "参数错误: "+err.Error())
		return
	}

	updateData := map[string]interface{}{
		"real_name": req.RealName,
		"phone":     req.Phone,
		"email":     req.Email,
	}

	err := ctrl.userService.UpdateUserByMap(userID.(uint), updateData)
	if err != nil {
		utils.ErrorWithMessage(c, "更新资料失败: "+err.Error())
		return
	}

	utils.SuccessWithMessage(c, "资料更新成功", nil)
}

// ChangePassword 修改密码
func (ctrl *UserController) ChangePassword(c *gin.Context) {
	userID, _ := c.Get("user_id")

	var req struct {
		OldPassword string `json:"old_password" binding:"required"`
		NewPassword string `json:"new_password" binding:"required,min=6"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.ErrorWithMessage(c, "参数错误: "+err.Error())
		return
	}

	err := ctrl.userService.UpdatePassword(userID.(uint), req.OldPassword, req.NewPassword)
	if err != nil {
		utils.ErrorWithMessage(c, "修改密码失败: "+err.Error())
		return
	}

	utils.SuccessWithMessage(c, "密码修改成功", nil)
}

// UsersIndex 用户管理页面
func (ctrl *UserController) UsersIndex(c *gin.Context) {
	c.HTML(http.StatusOK, "users/index.html", gin.H{
		"title":       "用户管理",
		"user":        c.MustGet("user"),
		"CurrentPage": "users",
		"HasPermission": func(permission string) bool {
			userID, _ := c.Get("user_id")
			return ctrl.permissionService.HasPermission(userID.(uint), permission)
		},
	})
}

// UserCreatePage 用户创建页面
func (ctrl *UserController) UserCreatePage(c *gin.Context) {
	c.HTML(http.StatusOK, "users/create.html", gin.H{
		"title":       "创建用户",
		"user":        c.MustGet("user"),
		"CurrentPage": "user-create",
	})
}

// UserEditPage 用户编辑页面
func (ctrl *UserController) UserEditPage(c *gin.Context) {
	id, _ := strconv.ParseUint(c.Param("id"), 10, 32)

	_, err := ctrl.userService.GetUserByID(uint(id))
	if err != nil {
		c.HTML(http.StatusNotFound, "errors/404.html", gin.H{
			"title": "用户不存在",
			"user":  c.MustGet("user"),
		})
		return
	}

	c.HTML(http.StatusOK, "users/edit.html", gin.H{
		"title":       "编辑用户",
		"user":        c.MustGet("user"),
		"user_id":     id,
		"CurrentPage": "user-edit",
	})
}

// UserDetailPage 用户详情页面
func (ctrl *UserController) UserDetailPage(c *gin.Context) {
	id, _ := strconv.ParseUint(c.Param("id"), 10, 32)

	_, err := ctrl.userService.GetUserByID(uint(id))
	if err != nil {
		c.HTML(http.StatusNotFound, "errors/404.html", gin.H{
			"title": "用户不存在",
			"user":  c.MustGet("user"),
		})
		return
	}

	c.HTML(http.StatusOK, "users/detail.html", gin.H{
		"title":       "用户详情",
		"user":        c.MustGet("user"),
		"user_id":     id,
		"description": "查看用户详细信息",
		"CurrentPage": "user-detail",
		"HasPermission": func(permission string) bool {
			userID, _ := c.Get("user_id")
			return ctrl.permissionService.HasPermission(userID.(uint), permission)
		},
	})
}

// ProfilePage 个人资料页面
func (ctrl *UserController) ProfilePage(c *gin.Context) {
	c.HTML(http.StatusOK, "system/profile.html", gin.H{
		"title": "个人资料",
		"user":  c.MustGet("user"),
	})
}
